# coding=utf-8

'''
根据歌手去找歌曲 一页20首歌 
然后根据歌名和歌手来下载歌曲和歌词
20首歌和歌词 接近1M/s的网速 花了33.9479383463s
author:insun
'''
import urllib,re,sys,os,time
reload(sys)
sys.setdefaultencoding('utf-8')
 
def musicScapy(singername):
    query =  urllib.quote(singername)
    url = 'http://music.baidu.com/search?key='+query
    response = urllib.urlopen(url)
    text = response.read()
    #<span class="song-title"  style="width: 170px;" ><a href="/song/7316463" class="" data-songdata='{ "id": "" }' title="爱情转移">爱情转移</a>
    reg = re.compile(r'<span class="song-title".+?>.+?<a.+?>(.*?)</a>',re.S)
    groups = re.findall(reg,text)
    '''判断目录songs和lrcs是否存在，不存在创建。否则报错'''
    if (os.path.exists('songs')== False):
        os.mkdir('songs')
    if(os.path.exists('lrcs') == False):
        os.mkdir('lrcs')
 
    for musicname in groups:
        try:
            xml =  urllib.urlopen('http://box.zhangmen.baidu.com/x?op=12&count=1&title='
                   + musicname+'$$'+singername +'$$').read()  
            encode =  re.compile('<encode>.*?CDATA\[(.*?)\]].*?</encode>',re.S).findall(xml)[0]  
            decode =  re.compile('<decode>.*?CDATA\[(.*?)\]].*?</decode>',re.S).findall(xml)[0]  
            lrcid =  re.compile('<lrcid>(.*?)</lrcid>',re.S).findall(xml)[0]
            #encode.rindex('/') 最后出现'/'的位置
            
            musicname = musicname.decode('utf-8')
            musiclink = encode[:encode.rindex('/')+1] + decode
            lrclink = 'http://box.zhangmen.baidu.com/bdlrc/'+str(int(lrcid)/100)+'/'+lrcid+'.lrc'
            #song download
            urllib.urlretrieve(musiclink,'songs/'+ musicname+'.mp3')
            #lrc download
            urllib.urlretrieve(lrclink,'lrcs/'+ musicname+'.lrc')
        
        except BaseException:
            print 'download failed'
            continue  
            
if __name__ == '__main__':
    beginTime = time.clock()
    musicScapy('陈奕迅')
    endTime = time.clock()
    print endTime-beginTime